package com.itheima.service.impl;

import com.itheima.mapper.UserMapper;
import com.itheima.pojo.User;
import com.itheima.qo.PageQuery;
import com.itheima.vo.PageResult;
import com.itheima.vo.UserLoginVo;
import com.itheima.service.UserService;
import com.itheima.utils.JwtUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequiredArgsConstructor
@Service
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;

    /***
     * 登录流程
     * @param user
     * @return
     */
    @Override
    public UserLoginVo login(User user) {
        //1、根据用户名查询用户是否存在
        User userInfo = userMapper.getByUsername(user.getUsername());

        //2、如果用户不存在，直接返回null
        if(userInfo == null){
            return null;
        }

        //3、用户存在，对前端传递的明文密码进行MD5加密
        String md5Password = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());

        //4、将加密后的密码与数据库中的密码进行比对
        if(!md5Password.equals(userInfo.getPassword())){
            return null;
        }

        //5、如果用户名和密码都正确，生成token令牌
        UserLoginVo vo = new UserLoginVo();
        BeanUtils.copyProperties(userInfo,vo);
        //生成token令牌
        Map<String,Object> payload = new HashMap<>();
        payload.put("id",userInfo.getId());
        payload.put("username",userInfo.getUsername());
        payload.put("name",userInfo.getName());
        String token = JwtUtils.generateJwt(payload);
        vo.setToken(token);
        return vo;
    }

    @Override
    public void add(User user) {
        // 为新用户设置默认密码
        if (user.getPassword() == null || user.getPassword().isEmpty()) {
            // 设置默认密码
            user.setPassword("123456");
        }
        // 对密码进行MD5加密
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        user.setCreateTime(LocalDateTime.now());
        userMapper.add(user);
    }

    @Override
    public User getById(Integer id) {return userMapper.getById(id);  }

    @Override
    public void update(User user) {
        // 如果密码不为空，则进行MD5加密
        if (user.getPassword() != null && !user.getPassword().isEmpty()) {
            user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        }
        userMapper.update(user);
    }

    @Override
    public void deleteById(Integer id) {
        userMapper.deleteById(id);
    }

    /***
     * 分页查询
     *      0）使用封装对象PageQuery接收前端传入的条件
     *      1）查询总数量     【有条件】->动态SQL
     *      2）分页查询      【有条件】->动态SQL
     *      3）响应数据->封装PageResult对象（分页）
     *          分页数据
     *          列表数据
     */
    @Override
    public PageResult page(PageQuery<User> pageQuery) {
        //1）查询总数量     【有条件】->动态SQL
        User user = pageQuery.getBody();
        long total = userMapper.count(user);
        //2）分页查询      【有条件】->动态SQL   limit #{索引},#{每页的条数}
        List<User> list = userMapper.list(pageQuery);

        int pages = (int) (total%pageQuery.getPageSize()==0? total/pageQuery.getPageSize():total/pageQuery.getPageSize()+1);
        PageResult pageResult = PageResult.builder()
                .currentPage(pageQuery.getPage())
                .total(total)
                .pages(pages)
                .build();
        //集合数据
        pageResult.setData(list);
        return pageResult;
    }


}
